package cn.itcast.spring;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:httpclient.properties")
public class HttpClientConfiguration {
	
	@Value("${httpclient.maxTotal}")
	private Integer maxTotal;
	@Value("${httpclient.defaultMaxPerRoute}")
	private Integer defaultMaxPerRoute;
	@Value("${httpclient.connectTimeout}")
	private Integer connectTimeout;
	@Value("${httpclient.connectionRequestTimeout}")
	private Integer connectionRequestTimeout;
	@Value("${httpclient.socketTimeout}")
	private Integer socketTimeout;
	@Value("${httpclient.staleConnectionCheckEnabled}")
	private Boolean staleConnectionCheckEnabled;

	@Bean
	public PoolingHttpClientConnectionManager cm() {
		// 初始化连接池管理器对象
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		// 设置最大连接数
		cm.setMaxTotal(maxTotal);
		// 设置每个主机地址的并发数
		cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
		return cm;
	}

	@Bean
	public RequestConfig config() {
		return RequestConfig.custom().setConnectTimeout(connectTimeout) // 创建连接的最长时间
				.setConnectionRequestTimeout(connectionRequestTimeout) // 从连接池中获取到连接的最长时间
				.setSocketTimeout(socketTimeout) // 数据传输的最长时间
				.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled) // 提交请求前测试连接是否可用
				.build();
	}

	@Bean
	public CloseableHttpClient closeableHttpClient(PoolingHttpClientConnectionManager cm, RequestConfig config) {
		return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).build();

	}
}
